import React, { useEffect, useState } from 'react';
import styles from './index.module.scss';
import { X } from 'lucide-react';
import { toast } from '@/components/basicComp/Toast';
import { installPlugin , addCustomPlugin} from '@/api/plugins';
import * as Switch from '@radix-ui/react-switch';
import * as Dialog from '@radix-ui/react-dialog';

const AddPluginModal = ({
  isAddCustomPluginOpen,
  pluginModalTitle,
  selectCustomPlugin: propSelectCustomPlugin,
  onOpenChange,
  getDiscoverList,
  getInstallList,
  pluginModalType
}) => {
  const [isJsonMode, setIsJsonMode] = useState(false);
  const [jsonConfig, setJsonConfig] = useState('');
  const [selectCustomPlugin, setSelectCustomPlugin] = useState(
    propSelectCustomPlugin || { newEnv: [], newArgs: [] }
  );

  useEffect(() => {
    if (propSelectCustomPlugin) {
      console.log(propSelectCustomPlugin,"propSelectCustomPlugin")
      setSelectCustomPlugin(propSelectCustomPlugin);
      setJsonConfig('');
      setIsJsonMode(false);
    }
  }, [propSelectCustomPlugin]);

  const getAddCustomPluginValue = () => {
    let newSelectCustomPlugin = { ...selectCustomPlugin };
    const { newEnv, newArgs, isEdit,...reqData } = newSelectCustomPlugin;
    let env = {};
    let args = [];
    let shouldContinue = true;
    // 检查是否是编辑状态且没有填写 server_name 或 command 
    if(!(newSelectCustomPlugin?.server_name?.trim())){
      toast.error('请填写Plugin Name');
      shouldContinue = false;
      return {shouldContinue}
    }
    // if(!newSelectCustomPlugin?.command?.trim()){
    //   toast.error('请填写Command');
    //   shouldContinue = false;
    //   return {shouldContinue}
    // }
    for (const item of newEnv || []) {
      //  检查 是否 是编辑状态且没有填写 key 或 value
      if (pluginModalType == 'edit' && (!item.key || !item.value)) {
        toast.error('请填写Environment Variable');
        shouldContinue = false;
        break;
      }
      if(pluginModalType == 'add' && !item.key) {
        toast.error('请填写Environment Variable Key');
        shouldContinue = false;
        break;
      }
      env[item.key] = item.value;
    }

    for (const item of newArgs || []) {
      if (!item.value) {
        toast.error('请填写Arguments');
        shouldContinue = false;
        break;
      }
      args.push(item.value);
    }

    reqData.env = env;
    reqData.args = args;

    return { shouldContinue, reqData };
  };

  const handleAddCustomPlugin = async () => {
    const { shouldContinue, reqData } = getAddCustomPluginValue();
    if (!shouldContinue) return;
    let rs = {};
    if(pluginModalType == 'install') {
       rs= await installPlugin(reqData);
    }
    if (pluginModalType == 'add') {
      rs = await addCustomPlugin(reqData);
    }
    if (rs.data?.code === 200) {
      getDiscoverList?.();
      getInstallList?.();
      onOpenChange(false);
      setSelectCustomPlugin({});
    } else {
      toast.error('添加插件失败');
    }
  };

  const getPluginChangeValue = (params) => {
    setSelectCustomPlugin((prev) => ({ ...prev, ...params }));
  };

  const handleJsonData = () => {

    console.log(selectCustomPlugin,"selectCustomPlugin")
    try {
      const jsonData = JSON.parse(jsonConfig)?.mcpServers || {};
      const [serverName, config] = Object.entries(jsonData)[0] || [];
      if (!serverName || !config) return;

      const transformed = {
        server_name: serverName,
        server_description: `Description for ${serverName}`,
        applied: selectCustomPlugin?.applie,
        execute_authorization: selectCustomPlugin?.execute_authorization,
        env: config.env || {},
        args: config.args || [],
        command: config.command || '',
      };

      const fromData = handleFormData(transformed);
      setSelectCustomPlugin(fromData);
      setIsJsonMode(false);
    } catch (err) {
      toast.error('JSON 格式错误');
    }
  };

  const handleFormData = (plugin) => {
    return {
      ...plugin,
      newEnv: Object.entries(plugin.env || {}).map(([key, value]) => ({
        key,
        value,
        isRequired: true
      })),
      newArgs: (plugin.args || []).map((value) => ({
        value,
        isRequired: true
      })),
      isEdit: selectCustomPlugin?.isEdit
    };
  };

  return (
    <div className={styles.container}>
      <Dialog.Root open={isAddCustomPluginOpen} onOpenChange={onOpenChange}>
        <Dialog.Portal>
          <Dialog.Overlay className={styles.dialogOverlay} />
          <Dialog.Content className={styles.dialogContent}>
            <div className={styles.dialogHeader}>
              <Dialog.Title className={styles.dialogTitle}>
                {pluginModalTitle}
              </Dialog.Title>
              <Dialog.Close asChild>
                <button className={styles.closeButton}>
                  <X size={18} />
                </button>
              </Dialog.Close>
            </div>

            <div className={styles.content}>
              <div className={styles.formGroup}>
                <label className={styles.formLabel}>Plugin Name</label>
                <input
                  type="text"
                  className={styles.formInput}
                  value={selectCustomPlugin?.server_name || ''}
                  onChange={(e) =>
                    getPluginChangeValue({ server_name: e.target.value })
                  }
                  placeholder="Google Workspace"
                />
              </div>

              <div className={`${styles.formGroup} ${styles.switchGroup}`}>
                <label className={styles.formLabel}>Enable Automatically</label>
                <Switch.Root
                  className={styles.switchRoot}
                  checked={selectCustomPlugin?.execute_authorization || true}
                  onCheckedChange={(e) =>
                    getPluginChangeValue({ execute_authorization: e })
                  }
                >
                  <Switch.Thumb className={styles.switchThumb} />
                </Switch.Root>
              </div>

              <div className={styles.formGroup}>
                <label className={styles.formLabel}>Command</label>
                <input
                  type="text"
                  className={styles.formInput}
                  value={selectCustomPlugin?.command || ''}
                  onChange={(e) =>
                    getPluginChangeValue({ command: e.target.value })
                  }
                  placeholder="Command"
                />
              </div>

              <div className={styles.formGroup}>
                <label className={styles.formLabel}>Environment Variable</label>
                {(selectCustomPlugin?.newEnv || []).map((item, index) => (
                  <div key={index} className={styles.variableRow}>
                    <input
                      type="text"
                      className={styles.formInput}
                      placeholder="Key"
                      value={item.key || ''}
                      onChange={(e) => {
                        const newEnv = [...selectCustomPlugin.newEnv];
                        newEnv[index].key = e.target.value;
                        getPluginChangeValue({ newEnv });
                      }}
                    />
                    <input
                      type="text"
                      className={styles.formInput}
                      placeholder="Value"
                      value={item.value || ''}
                      onChange={(e) => {
                        const newEnv = [...selectCustomPlugin.newEnv];
                        newEnv[index].value = e.target.value;
                        getPluginChangeValue({ newEnv });
                      }}
                    />
                  </div>
                ))}
                {!selectCustomPlugin?.isEdit && (
                  <div>
                    <button
                      className={styles.addVariableButton}
                      onClick={() => {
                        const newEnv = [
                          ...(selectCustomPlugin.newEnv || []),
                          { key: null, isRequired: false, value: null }
                        ];
                        getPluginChangeValue({ newEnv });
                      }}
                    >
                      +Add Variable
                    </button>
                    {selectCustomPlugin?.newEnv?.length >= 1 && (
                      <button
                        className={styles.addVariableButton}
                        onClick={() => {
                          const newEnv = [...selectCustomPlugin.newEnv];
                          newEnv.pop();
                          getPluginChangeValue({ newEnv });
                        }}
                      >
                        -Delete
                      </button>
                    )}
                  </div>
                )}
              </div>

              <div className={styles.formGroup}>
                <label className={styles.formLabel}>Arguments</label>
                {(selectCustomPlugin?.newArgs || []).map((item, index) => (
                  <input
                    key={index}
                    type="text"
                    className={styles.formInput}
                    placeholder="Arguments"
                    value={item.value || ''}
                    onChange={(e) => {
                      const newArgs = [...selectCustomPlugin.newArgs];
                      newArgs[index].value = e.target.value;
                      getPluginChangeValue({ newArgs });
                    }}
                    style={{ marginBottom: '10px' }}
                  />
                ))}
                {!selectCustomPlugin?.isEdit && (
                  <div>
                    <button
                      className={styles.addArgumentButton}
                      onClick={() => {
                        const newArgs = [
                          ...(selectCustomPlugin.newArgs || []),
                          { isRequired: false, value: null }
                        ];
                        getPluginChangeValue({ newArgs });
                      }}
                    >
                      +Add Argument
                    </button>
                    {selectCustomPlugin?.newArgs?.length >= 1 && (
                      <button
                        className={styles.addArgumentButton}
                        onClick={() => {
                          const newArgs = [...selectCustomPlugin.newArgs];
                          newArgs.pop();
                          getPluginChangeValue({ newArgs });
                        }}
                      >
                        -Delete
                      </button>
                    )}
                  </div>
                )}
              </div>
            </div>

            {!selectCustomPlugin?.isEdit && (
              <>
                <div
                  className={styles.jsonModeLink}
                  onClick={() => {
                    setJsonConfig('')
                    setIsJsonMode(!isJsonMode)
                  }}
                >
                  {isJsonMode ? 'Form Mode' : 'JSON Mode'}
                </div>

                <div className={styles.dialogFooter}>
                  <Dialog.Close asChild>
                    <button className={styles.cancelButton}>Cancel</button>
                  </Dialog.Close>
                  <button
                    className={styles.addButton}
                    onClick={handleAddCustomPlugin}
                  >
                    Add
                  </button>
                </div>
              </>
            )}

            <div
              style={{
                opacity: isJsonMode ? 1 : 0,
                zIndex: isJsonMode ? 100 : -3
              }}
              className={styles.modalWrapper}
              onClick={() => setIsJsonMode(false)}
            >
              <div className={styles.content}>
                <h2 className={styles.title}>Add JSON Configuration</h2>
                <button
                  className={styles.closeButton}
                  onClick={() => setIsJsonMode(false)}
                >
                  <X size={18} />
                </button>

                <div className={styles.formGroup}>
                  <label className={styles.label}>JSON Configuration</label>
                  <textarea
                    className={styles.textarea}
                    value={jsonConfig}
                    onChange={(e) => setJsonConfig(e.target.value)}
                    placeholder='{"mcpServers": {}}'
                    onClick={(e) => e.stopPropagation()}
                    rows={6}
                  />
                </div>

                <div className={styles.buttonGroup}>
                  <button
                    className={styles.secondaryButton}
                    onClick={() => setIsJsonMode(false)}
                  >
                    Cancel
                  </button>
                  <button
                    className={styles.primaryButton}
                    onClick={(e) => {
                      e.stopPropagation();
                      handleJsonData();
                    }}
                  >
                    Add
                  </button>
                </div>
              </div>
            </div>
          </Dialog.Content>
        </Dialog.Portal>
      </Dialog.Root>
    </div>
  );
};

export default AddPluginModal;
